import React, { useState, useRef, useEffect } from "react";
import { motion } from "framer-motion";
import { Image } from "antd";
const SearchBar: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const searchContainerRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // 点击外部关闭搜索层
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        searchContainerRef.current &&
        !searchContainerRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      // 自动聚焦输入框
      setTimeout(() => inputRef.current?.focus(), 100);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen]);

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    if (e.key == "Enter") {
      e.preventDefault();
      if (searchValue.trim()) {
        setSearchHistory(
          (prev) => [searchValue, ...prev].slice(0, 5) // 保留最近5条记录
        );
        console.log("Searching:", searchValue);
        // 实际搜索逻辑...
        setSearchValue(""); // 清空搜索框
      }
    }
  };

  // 点击历史记录填充搜索框
  const fillSearch = (text: string) => {
    setSearchValue(text);
    inputRef.current?.focus();
  };
  const clearHistory = () => {
    setSearchHistory([]); // 清空搜索历史
  };

  return (
    <div className="search-bar">
      {!isOpen && (
        <div>
          <Image
            preview={false}
            height={"50px"}
            width={"50px"}
            src="../imgs/商标1.jpg"
          />
        </div>
      )}

      <div className="search-popup-container" ref={searchContainerRef}>
        {/* 搜索按钮 */}
        <div>
          <motion.div
            className="search-input-wrapper"
            layout // 保持布局动画
          >
            <input
              ref={inputRef}
              type="text"
              value={searchValue}
              onKeyDown={(e) => {
                handleSearch(e);
              }}
              onChange={(e) => setSearchValue(e.target.value)}
              placeholder="搜索商品"
              className={`search-input ${isOpen ? "expanded" : ""}`}
            />
            {!isOpen ? (
              <div
                className="iconfont icon-sousuo"
                onClick={() => setIsOpen(true)}
              ></div>
            ) : (
              <button
                className="search-close"
                onClick={() => setIsOpen(false)}
              >
                ×
              </button>
            )}
          </motion.div>

          {/* 搜索历史 */}
          {searchHistory.length > 0 && isOpen && (
            <motion.div
              className="search-history"
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
            >
              <div className="search-div">
              <h4>最近搜索</h4>
              <p className="iconfont icon-huishouzhan"
                 onClick={clearHistory}
              ></p>
              </div>
              
              <ul>
                {searchHistory.map((item, index) => (
                  <li key={index} onClick={() => fillSearch(item)}>
                    {item}
                  </li>
                ))}
              </ul>
            </motion.div>
          )}
        </div>
      </div>
    </div>
  );
};

export default SearchBar;
